package com.taylor.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.*;

/**
 * @Desc : bio demo
 * @Author ： taylor
 * @Date ：2021/6/25 22:49
 */
public class BIOServer {

    public static void main(String[] args) throws IOException {

        //创建一个线程池
        ExecutorService newCachedThreadPool = newCachedThreadPool();

        try (ServerSocket serverSocket = new ServerSocket(8888);
             Socket socket = serverSocket.accept();
             InputStream inputStream = socket.getInputStream()){
            System.out.println("服务器启动了");
            while (true) {
                System.out.println("线程信息id = " + Thread.currentThread().getId() + "名字 = " + Thread.currentThread().getName());
                //监听，等待客户端连接
                System.out.println("等待连接....阻塞中.....");
                System.out.println("连接到一个客户端");
                //就创建一个线程，与之通讯(单独写一个方法)
                newCachedThreadPool.execute(() -> {
                    //可以和客户端通讯
                    byte[] buffer = new byte[1024];
                    //循环的读取客户端发送的数据
                    while (true) {
                        System.out.println("线程信息id = " + Thread.currentThread().getId() + "名字 = " + Thread.currentThread().getName());
                        System.out.println("read....阻塞中......");
                        int len = 0;
                        try {
                            len = inputStream.read(buffer);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (len != -1) {
                            //输出客户端发送的数据
                            System.out.println(new String(buffer, 0, len));
                        } else {
                            break;
                        }
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
